package com.ytjj.qmyx.admin.controller;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.ReplyRecordResponse;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.request.NewImportOrderRequest;
import com.ytjj.qmyx.admin.model.request.complaints.AliPayComplaintsImportRequest;
import com.ytjj.qmyx.admin.service.AliPayComplaintsService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 支付宝投诉相关接口
 */
@RestController
@RequestMapping("/alipayComplaints")
@Slf4j
@RefreshScope
public class AliPayComplaintsController {

    @Resource
    private AliPayComplaintsService aliPayComplaintsService;
    @Resource
    private MallClient mallClient;
    @Resource
    private RedisService redisService;

    /**
     * 查询投诉单协商历史
     * @param complainEventId
     * @return
     * @throws Exception
     */
    @GetMapping("/queryComplaintsHistory")
    public CommonResult<List<ReplyRecordResponse>> queryComplaintsHistory(@RequestParam String complainEventId) throws Exception{
        return CommonResult.success(aliPayComplaintsService.queryComplaintsHistory(complainEventId));
    }

    /**
     * 查询支付宝投诉列表
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/aliPayComplaintsList")
    public CommonResult<CommonPage<AliPayComplaintsListResponse>> aliPayComplaintsList(@RequestBody AliPayComplaintsListRequest request) throws Exception {
        return CommonResult.success(aliPayComplaintsService.aliPayComplaintsList(request));
    }


    /**
     * 删除投诉记录
     * @param ids 唯一标识
     * @return CommonResult
     */
    @PostMapping("/delTradeComplaints")
    public CommonResult delTradeComplaints(@RequestBody List<Integer> ids) {
        String error = aliPayComplaintsService.delTradeComplaints(ids);
        return StringUtils.isNotBlank(error) ? CommonResult.failed(error) : CommonResult.success(error);
    }


    /**
     * 处理投诉记录
     */
    @GetMapping("/markComplaintStatus")
    public CommonResult markComplaintStatus(String complainEventId, String statusStr) {
        Integer integer = aliPayComplaintsService.markComplaintStatus(complainEventId, statusStr);
        return integer == 1 ? CommonResult.success() : CommonResult.failed();
    }


    /**
     * 回复用户
     * @param replyRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/complaintsReplySubmit")
    CommonResult complaintsReplySubmit(@RequestBody AliPayComplatintsReplyRequest replyRequest) throws Exception{
        Integer adminId = UserUtil.getAdminId();
        replyRequest.setAdminId(adminId);
        //保存输截取后的字符串到缓存，方便下次用
        if (null != replyRequest.getTemplateValue() && !CollectionUtils.isEmpty(replyRequest.getPlaceHolders())) {
            redisService.set(RedisConstants.MSG_TEMPLATE_VARIABLE_KEY + ":" + replyRequest.getTemplateValue() + ":" + adminId, JSON.toJSONString(replyRequest.getPlaceHolders()));
        }
        return mallClient.complaintsReplySubmit(replyRequest);
    }

    /**
     * 反馈处理完成
     * @param feedbackRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/complaintsFeedbackSubmit")
    CommonResult complaintsFeedbackSubmit(@RequestBody AliPayComplatintsFeedbackRequest feedbackRequest)throws Exception{
        Admin admin = UserUtil.getAdminData();
        feedbackRequest.setAdminId(admin.getId());
        feedbackRequest.setAdminName(admin.getName());
        return mallClient.complaintsFeedbackSubmit(feedbackRequest);
    }

    /**
     * 支付宝投诉上传反馈图片
     */
    @PostMapping("/upload")
    public CommonResult getImgUrl(@RequestParam("file") MultipartFile file, @RequestParam("complainEventId") String complainEventId) throws Exception{
        return CommonResult.success(aliPayComplaintsService.getImgUrl(file,complainEventId));
    }

    /**
     * 商家补充凭证
     * @param supplementRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/complaintsSupplementSubmit")
    CommonResult complaintsSupplementSubmit(@RequestBody AliPayComplatintsSupplementRequest supplementRequest)throws Exception{
        if (StringUtils.isBlank(supplementRequest.getSupplementContent()) && CollectionUtils.isEmpty(supplementRequest.getSupplementImages())) {
            throw new ApiException("文字凭证和图片凭证不能同时为空!");
        }
        return mallClient.complaintsSupplementSubmit(supplementRequest);
    }

    /**
     * 支付宝交易投诉导入
     */
    @PostMapping("/importComplaints")
    public CommonResult importComplaints(MultipartFile file) {
        Sheet sheet = new Sheet(1, 1, AliPayComplaintsImportRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            //处理数据
            String message = aliPayComplaintsService.importComplaints(list.stream()
                    .map(item -> {
                        Field[] fields = item.getClass().getDeclaredFields();
                        Arrays.stream(fields).filter(field -> field.getType() == String.class).forEach(field -> {
                                    try {
                                        field.setAccessible(true); // 允许访问私有字段
                                        String value = (String) field.get(item);
                                        if (null != value) {
                                            field.set(item, value.trim());
                                        }
                                    } catch (IllegalAccessException e) {
                                        // 处理访问权限问题
                                        log.error("数据访问权限问题");
                                    }
                                });
                        return (AliPayComplaintsImportRequest) item;
                    })
                    .collect(Collectors.toList()));
            return CommonResult.success(message);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导入发生异常：{}", e.getMessage());
        }
        return  CommonResult.failed(ResultCode.FAILED);
    }

    public class ObjectUtils {

        /**
         * 清除对象所有字符串属性的空白字符。
         *
         * @param obj 对象实例
         */
        public void removeEmptyStringsFromFields(Object obj) {
            if (obj == null) {
                return;
            }

            Field[] fields = obj.getClass().getDeclaredFields();
            Arrays.stream(fields)
                    .filter(field -> field.getType() == String.class)
                    .forEach(field -> {
                        try {
                            field.setAccessible(true); // 允许访问私有字段
                            String value = (String) field.get(obj);
                            if (value != null && value.trim().isEmpty()) {
                                field.set(obj, null); // 或者你想设置为其他默认值，比如""
                            }
                        } catch (IllegalAccessException e) {
                            // 处理访问权限问题
                            e.printStackTrace();
                        }
                    });
        }
    }

}
